var studentLen;
$.ajax({
    url: '/class/list',
    type: 'GET',
    data:{
        teacherName:$.cookie("teacherName")
    },
    async: false,
    success: function (data) {
        var arr = data.data;
        document.getElementById('studentclassName').innerHTML = '';
        var option = document.createElement('option');
        option.value = '';
        option.text = '请选择班级';
        document.getElementById('studentclassName').appendChild(option);
        for (let i = 0; i < arr.length; i++) {
            var option = document.createElement('option');
            option.value = arr[i].className;
            option.text = arr[i].className;
            document.getElementById('studentclassName').appendChild(option);
        }
        document.getElementById("className").innerHTML="";
        for (let i = 0; i < arr.length; i++) {
            var option = document.createElement('option');
            option.value = arr[i].className;
            option.text = arr[i].className;
            document.getElementById("className").appendChild(option);
        }
    }
})
// 模拟数据

let students = [
    { id: 1, name: '张三', avatar: 'https://randomuser.me/api/portraits/men/1.jpg', age: 20, sex: '男', className: '计算机1班', sno: '2021001', phone: '13800138001' },
    { id: 2, name: '李四', avatar: 'https://randomuser.me/api/portraits/women/1.jpg', age: 21, sex: '女', className: '计算机2班', sno: '2021002', phone: '13800138002' },
    { id: 3, name: '王五', avatar: 'https://randomuser.me/api/portraits/men/2.jpg', age: 22, sex: '男', className: '计算机1班', sno: '2021003', phone: '13800138003' },
    { id: 4, name: '赵六', avatar: 'https://randomuser.me/api/portraits/women/2.jpg', age: 19, sex: '女', className: '计算机3班', sno: '2021004', phone: '13800138004' },
    { id: 5, name: '钱七', avatar: 'https://randomuser.me/api/portraits/men/3.jpg', age: 20, sex: '男', className: '计算机2班', sno: '2021005', phone: '13800138005' },
    { id: 6, name: '孙八', avatar: 'https://randomuser.me/api/portraits/women/3.jpg', age: 21, sex: '女', className: '计算机1班', sno: '2021006', phone: '13800138006' },
    { id: 7, name: '周九', avatar: 'https://randomuser.me/api/portraits/men/4.jpg', age: 22, sex: '男', className: '计算机3班', sno: '2021007', phone: '13800138007' },
    { id: 8, name: '吴十', avatar: 'https://randomuser.me/api/portraits/women/4.jpg', age: 20, sex: '女', className: '计算机2班', sno: '2021008', phone: '13800138008' }
];

const loader = document.getElementById('compact-loader');
// DOM元素
const tableBody = document.getElementById('tableBody');
const pageNumbers = document.getElementById('pageNumbers');
const prevPage = document.getElementById('prevPage');
const nextPage = document.getElementById('nextPage');
const addBtn = document.getElementById('addBtn');
const studentModal = document.getElementById('studentModal');
const closeModal = document.getElementById('closeModal');
const studentForm = document.getElementById('studentForm');
const modalTitle = document.getElementById('modalTitle');
const analysisModal = document.getElementById('analysisModal');
const analysisContent = document.getElementById('analysisContent');
const closeAnalysisModal = document.getElementById('closeAnalysisModal');
const cancelAnalysis = document.getElementById('cancelAnalysis');
const downloadBtn = document.getElementById('downloadBtn');
const avatarInput = document.getElementById('avatar');
const avatarPreview = document.getElementById('avatarPreview');
const pageSizeSelect = document.getElementById('pageSize');
const studentname = document.getElementById('studentname');
const studentphone = document.getElementById('studentphone');
const studentclassName = document.getElementById('studentclassName');
const searchBtn = document.querySelector('.btnSearch');
const avaterimg = document.querySelector(".avatar")
const btnSubmit = document.querySelector(".btn-submit");
// 分页变量
let currentPage = 1;
let rowsPerPage = parseInt(pageSizeSelect.value); // 从选择器获取初始值
let totalPages = Math.ceil(students.length / rowsPerPage);
let imgSrc = '';
// 当前选中的学生ID
let currentStudentId = null;
// 初始化页面
function init() {
    renderTable();
    renderPagination();
    addEventListeners();
}

// 渲染表格
function renderTable() {
    console.log(currentPage+"当前页")
    const className = studentclassName.value || '';
    tableBody.innerHTML = '';
    $.ajax({
        url: '/student/list',
        type: 'POST',
        // 等待
        async: false,
        data:{
            name:studentname.value,
            phone:studentphone.value,
            className:className,
            page:currentPage,
            pageSize:pageSizeSelect.value,
            teacherName:$.cookie("teacherName")
        },
        success: function (data) {
            console.log(data)
            students = data.data.rows;
            studentLen = data.data.total;
        }
    })
    const paginatedStudents = students;
    tableBody.innerHTML=""
    paginatedStudents.forEach(student => {
        console.log(1)
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${student.id}</td>
<td>${student.name}</td>
<td>
    ${student.icon ?
            `<img src="${student.icon}" class="avatar" alt="${student.name}的头像">` :
            `<i class="fas fa-user-circle avatar-placeholder"></i>`}
</td>
<td>${student.age}</td>
<td>${student.sex}</td>
<td>${student.className}</td>
<td>${student.sno}</td>
<td>${student.phone}</td>
<td>
    <button class="btn-edit" data-id="${student.id}">
        <i class="fas fa-edit"></i> 修改
    </button>
    <button class="btn-delete" data-id="${student.id}">
        <i class="fas fa-trash"></i> 删除
    </button>
</td>
<td>
    <button class="btn-ai" data-id="${student.id}">
        <i class="fas fa-robot"></i> AI分析
    </button>
</td>
        `;
        tableBody.appendChild(row);
    });
}

// 渲染分页
function renderPagination() {
    pageNumbers.innerHTML = '';
    totalPages = Math.ceil(studentLen / rowsPerPage);
    console.log(studentLen+"总数")
    // 上一页按钮状态
    prevPage.disabled = currentPage === 1;

    // 页码按钮
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    if (startPage > 1) {
        const firstPage = document.createElement('button');
        firstPage.className = 'page-number';
        firstPage.textContent = '1';
        firstPage.addEventListener('click', () => goToPage(1));
        pageNumbers.appendChild(firstPage);

        if (startPage > 2) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            pageNumbers.appendChild(ellipsis);
        }
    }

    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `page-number ${i === currentPage ? 'active' : ''}`;
        pageBtn.textContent = i;
        pageBtn.addEventListener('click', () => goToPage(i));
        pageNumbers.appendChild(pageBtn);
    }

    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            pageNumbers.appendChild(ellipsis);
        }

        const lastPage = document.createElement('button');
        lastPage.className = 'page-number';
        lastPage.textContent = totalPages;
        lastPage.addEventListener('click', () => goToPage(totalPages));
        pageNumbers.appendChild(lastPage);
    }

    // 下一页按钮状态
    nextPage.disabled = currentPage === totalPages || totalPages === 0;
}

// 跳转到指定页码
function goToPage(page) {
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    console.log(page+"当前页")
    renderTable();
    renderPagination();
}

// 添加事件监听器
function addEventListeners() {
    // 分页按钮
    prevPage.addEventListener('click', () => goToPage(currentPage - 1));
    nextPage.addEventListener('click', () => goToPage(currentPage + 1));

    // 每页显示条数选择器
    pageSizeSelect.addEventListener('change', (e) => {
        rowsPerPage = parseInt(e.target.value);
        currentPage = 1; // 重置到第一页
        renderTable();
        renderPagination();
    });
    searchBtn.addEventListener('click', ()=>{
        renderTable()
        renderPagination();
    })
    // 添加按钮
    addBtn.addEventListener('click', () => {
        console.log(1)
        studentForm.reset();
        document.getElementById('studentId').value = '';
        avatarPreview.innerHTML = '<img src="" class="avatar_insert" alt="预览头像">';
        modalTitle.textContent = '添加学生信息';
        studentModal.classList.add('show');
    });

    // 关闭模态框
    closeModal.addEventListener('click', () => {
        studentModal.classList.remove('show');
    });

    closeAnalysisModal.addEventListener('click', () => {
        analysisModal.classList.remove('show');
    });

    cancelAnalysis.addEventListener('click', () => {
        analysisModal.classList.remove('show');
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        if (e.target === studentModal) {
            studentModal.classList.remove('show');
        }
        if (e.target === analysisModal) {
            analysisModal.classList.remove('show');
        }
    });

    // 头像上传
    avatarInput.addEventListener('change', (e) => {
        const file =  avatarInput.files[0];
        const formData = new FormData();
        formData.append("file", file);  // "file" 必须和后端参数名一致
        $.ajax({
            url: "/upload",  // 替换为你的Servlet URL
            type: "POST",
            data: formData,
            processData: false,      // 禁止jQuery处理数据（文件上传必须）
            contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
            cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
            success: function (response) {
                imgSrc = response.data
                console.log(imgSrc)
                document.querySelector(".avatar_insert")?document.querySelector(".avatar_insert").src = imgSrc:null;
                document.querySelector(".avatar_update")?document.querySelector(".avatar_update").src= imgSrc :null;
            },error: function(xhr, status, error) {
                console.error("上传失败:", error);
                $("#result").html("上传失败: " + (xhr.responseText || error));
            }
        });
    });

    // 表单提交
    studentForm.addEventListener('submit', (e) => {
        e.preventDefault();

        const id = document.getElementById('studentId').value;
        const avatar = avatarPreview.querySelector('img')?.src || '';

        const studentData = {
            name: document.getElementById('name').value,
            icon: imgSrc,
            age: parseInt(document.getElementById('age').value),
            sex: document.querySelector('input[name="sex"]:checked').value,
            className: document.getElementById('className').value,
            sno: document.getElementById('sno').value,
            phone: document.getElementById('phone').value,
            password:123456,
            id:null
        };

        if (id) {
            // 编辑现有学生
            const index = students.findIndex(s => s.id == id);
            if (index !== -1) {
                students[index] = { ...students[index], ...studentData };
            }
            studentData.id = id
            $.ajax( {
                url: "/student/updatestudent",
                type: "POST",
                async:false,
                data: studentData,
                success: function (response) {
                    console.log(response)
                },error:function (){
                    $("#error-message").text("更改学生失败，已有该学生的信息")
                    $(".alert-danger").show();
                    setTimeout(function () {
                        $(".alert-danger").hide();
                    }, 1200);

                }
            })
        } else {
            console.log(studentData)
            // 添加新学生
            const newId = students.length > 0 ? Math.max(...students.map(s => s.id)) + 1 : 1;
            students.push({ id: newId, ...studentData });
            var flag = true
            $.ajax( {
                url: "/student/findRepeatMessage",
                type: "POST",
                async:false,
                data: studentData,
                success: function (response) {
                    console.log(response)
                    if(response.code != 200){
                        flag = false;
                        $("#error-message").text("添加学生失败，已有该学生的信息")
                        $(".alert-danger").show();
                        setTimeout(function () {
                            $(".alert-danger").hide();
                        }, 1200);
                    }
                }
            })
            if(flag){
                $.ajax( {
                    url: "/student/addstudent",
                    type: "POST",
                    data: studentData,
                    success: function (response) {
                        console.log(response)
                        $("#success-message").text("学生添加成功")
                        $(".alert-success").show();
                        setTimeout(function () {
                            $(".alert-success").hide();
                        }, 1200);

                    }
                })
            }

        }
        studentModal.classList.remove('show');
        renderTable();
        renderPagination();
    });

    // 表格按钮事件委托
    tableBody.addEventListener('click', (e) => {
        const target = e.target.closest('button');
        if (!target) return;

        const id = parseInt(target.getAttribute('data-id'));
        const student = students.find(s => s.id === id);
        if (!student) return;

        if (target.classList.contains('btn-edit')) {
            // 编辑按钮
            modalTitle.textContent = '编辑学生信息';
            document.getElementById('studentId').value = student.id;
            document.getElementById('name').value = student.name;
            document.getElementById('age').value = student.age;
            document.querySelector(`input[name="sex"][value="${student.sex}"]`).checked = true;
            document.getElementById('className').value = student.className;
            document.getElementById('sno').value = student.sno;
            document.getElementById('phone').value = student.phone;
            console.log(student.icon)
            console.log("编辑模式")
            // 设置头像预览
            avatarPreview.innerHTML =
                `<img src="${student.icon}" class="avatar_update" alt="预览头像">`

            studentModal.classList.add('show');
        } else if (target.classList.contains('btn-delete')) {
            // 删除按钮
            if (confirm(`确定要删除学生 ${student.name} 吗？`)) {
                students = students.filter(s => s.id !== id);
                $.ajax( {
                    url: "/student/deletestudent",
                    type: "POST",
                    async:false,
                    data: {id:id},
                    success: function (response) {
                        console.log(response)
                        $("#success-message").text("学生删除成功")
                        $(".alert-success").show();
                        setTimeout(function () {
                            $(".alert-success").hide();
                        }, 1200);

                    }
                })
                renderTable();
                renderPagination();
            }
        } else if (target.classList.contains('btn-ai')) {
            var hasAIResult = false;
            var data = null;
            // AI分析按钮
            currentStudentId = id;
            console.log(student.name+"1111")
            $.ajax({
                url: "/student/findMessage",
                type: "POST",
                async:false,
                data: {name:student.name},
                success: function (response) {
                    if(response.data.length != 0){
                        hasAIResult = true
                        data = response.data[0];
                    }
                    console.log(data)
                }
            })
            console.log(hasAIResult)
            if(hasAIResult){
                showConfirm("是否重新进行AI分析？", function(){
                    //重新分析的情况吗
                    loader.style.display = 'flex';
                    setTimeout(() => {
                        analyzeStudent(student);
                    }, 20);
                }, function(){
                    console.log("不计算")
                    // 不重新分析的情况
                    const content =data.paper;
                    // 模拟AI分析
                    document.querySelector(".elegant-report").innerHTML= marked.parse(content.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>'));

                    analysisModal.classList.add('show');
                    $("#downloadBtn").attr("href",data.pdf)
                })
            }else{
                loader.style.display = 'flex';
                setTimeout(() => {
                    analyzeStudent(student);
                }, 20);
            }
        }
    });

    // 下载按钮
    downloadBtn.addEventListener('click', () => {
        const student = students.find(s => s.id === currentStudentId);
        if (student) {
            alert(`正在下载 ${student.name} 的分析报告Word文档`);
        }
        $("#success-message").text("学生分析word下载成功")
        $(".alert-success").show();
        setTimeout(function () {
            $(".alert-success").hide();
        }, 1200);

    });
}

// AI分析学生
function analyzeStudent(student) {
// 显示加载动画
    loader.style.opacity = '1';

    $.ajax({
        url: "/student/AnalyzeAllStudentInfo",
        type: "POST",
        cache: false,
        data: { name: student.name },
        success: function(response) {
            console.log(response);
            const content = response.data.res; // 确保路径正确
            document.querySelector(".elegant-report").innerHTML = marked.parse(
                content.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
            );
            $("#downloadBtn").attr("href", response.data.url);
            $("#success-message").text("学生分析完成");
            $(".alert-success").show().delay(1200).fadeOut();
        },
        error: function(xhr, status, error) {
            console.error("请求失败:", error);
            $("#error-message").text("分析失败: " + error).show().delay(1200).fadeOut();
        },
        complete: function() {
            loader.style.opacity = '0'; // 无论成功失败都隐藏加载动画
            analysisModal.classList.add('show');
        }
    });
}

// 随机生成潜力评价


// 随机生成建议


// 初始化应用
document.addEventListener('DOMContentLoaded', init);

// 显示确认框的函数
function showConfirm(message, yesCallback, noCallback) {
    const confirmModal = document.getElementById('confirmModal');
    const confirmContent = document.getElementById('confirmContent');
    const confirmYes = document.getElementById('confirmYes');
    const confirmNo = document.getElementById('confirmNo');
    const closeConfirmModal = document.getElementById('closeConfirmModal');
    // 设置提示内容
    confirmContent.textContent = message;

    console.log(11)
    // 显示模态框
    confirmModal.style.display = 'flex';

    // 设置按钮事件
    confirmYes.onclick = function() {
        confirmModal.style.display = 'none';
        if (yesCallback) yesCallback();
    };

    confirmNo.onclick = function() {
        confirmModal.style.display = 'none';
        if (noCallback) noCallback();
    };

    closeConfirmModal.onclick = function() {
        confirmModal.style.display = 'none';
        // if (noCallback) noCallback();
    };

    // 点击模态框外部关闭
    window.onclick = function(event) {
        if (event.target == confirmModal) {
            confirmModal.style.display = 'none';
        }
    };
}
